package com.syqc.videos.real

import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.syqc.base.BaseRealFragment
import com.syqc.comlib.utils.toast
import com.syqc.entity.RealVideoInfo
import com.syqc.monitor.R
import com.syqc.monitor.databinding.FragChannelBinding

/**
 *@author  hfjs
 *@time   2024/12/31 11:21
 *@desc
 */
class ChannelFragment(
    private val type: Int,
    private val itemCall: (MutableList<RealVideoInfo>) -> Unit
) :
    BaseRealFragment<FragChannelBinding>(type, FragChannelBinding::inflate) {
    private val mAdapter by lazy { ChannelAdapter() }
    override fun hide() {

    }

    override fun initView(view: View) {
        binding.rvChannel.layoutManager = GridLayoutManager(requireContext(), 3)
        binding.rvChannel.adapter = mAdapter
    }

    override fun initData() {

    }

    override fun initEvent() {
        mAdapter.setOnItemClickListener { adapter, _, position ->
            val item = mAdapter.data[position]

            if (hasChecked()) {
                item.isChecked = !item.isChecked
                adapter.notifyItemChanged(position)
                itemCall(mAdapter.data)
            } else {
                if (!item.isChecked) {
                    item.isChecked = true
                    adapter.notifyItemChanged(position)
                    itemCall(mAdapter.data)
                } else {
                    R.string.toast_one_pass.toast(requireContext())
                }
            }
        }
    }

    fun setChannels(channels: MutableList<RealVideoInfo>) {
        mAdapter.setList(channels)
    }

    private fun hasChecked(): Boolean {
        val list = mAdapter.data.filter { it.isChecked }

        return list.size > 1
    }
}

class ChannelAdapter : BaseQuickAdapter<RealVideoInfo, BaseViewHolder>(R.layout.item_channel) {
    override fun convert(holder: BaseViewHolder, item: RealVideoInfo) {
        holder.setText(R.id.tvChannel, item.videoName)
        holder.itemView.isSelected = item.isChecked
    }
}